<!--
 * @Author: zxm 308370383@qq.com
 * @Date: 2022-05-10 16:47:55
 * @LastEditors: zxm 308370383@qq.com
 * @LastEditTime: 2022-05-31 14:43:09
 * @FilePath: \0421\歌曲列表2.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>歌曲列表</h1>
    <audio controls src=""></audio>
    <ul class="ul">
    </ul>
    <script>
        // 封装作为一个共用的函数
        function getXHR(url) {
            var oAjax = new XMLHttpRequest();
            oAjax.open('get', url)
            oAjax.send();
            oAjax.onreadystatechange = function () {
                // debugger
                if (oAjax.readyState == 4) {
                    if (oAjax.status == 200) {
                        var res = JSON.parse(oAjax.responseText);
                        // 歌曲列表
                        var list = res.result;
                        var oUl = document.querySelector('.ul');
                        var str = ''
                        for (var i = 0; i < list.length; i++) {
                            // 字符串拼接
                            str += "<li><img onclick=change(" + list[i].id + ") class='img' src=" + list[i].picUrl + " width=100>" +
                                "<span class='name'>" + list[i].name + "</span>" +
                                "<button onclick=play(" + list[i].id + ") class='btn'>play</button></li>"
                        }
                        oUl.innerHTML = str
                    }

                }
            }
        }
        window.onload = function () {
            getXHR('http://localhost:3000/personalized/newsong');
        }
        function change(id) {
            // console.log(id);
            window.open('./detail.html?id=' + id)
        }
        function play(id) {
            var oAjax = new XMLHttpRequest();
            oAjax.open('get', 'http://localhost:3000/song/url?id=' + id)
            oAjax.send();
            oAjax.onreadystatechange = function () {
                if (oAjax.readyState == 4) {
                    if (oAjax.status == 200) {
                        var data = JSON.parse(oAjax.responseText)
                        console.log(data.data[0].url);
                        var oAudio = document.querySelector('audio');
                        oAudio.src = data.data[0].url;
                    }
                }
            }
        }
    </script>
</body>

</html>
